package com.maimao.core.interceptor;

import com.maimao.core.utils.ThreadLocalUtil;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import io.seata.core.context.RootContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.Map;

/**
 * Feign拦截器
 *
 * @author MaoLin Wang
 * @date 2020/11/29 10:28 下午
 */
@Configuration
public class FeignInterceptor implements RequestInterceptor {


    @Override
    public void apply(RequestTemplate requestTemplate) {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (requestAttributes != null) {
            HttpServletRequest request = requestAttributes.getRequest();
            //取出当前请求的header，找到jwt令牌
            Enumeration<String> headerNames = request.getHeaderNames();
            if (headerNames != null) {
                while (headerNames.hasMoreElements()) {
                    String headerName = headerNames.nextElement();
                    String headerValue = request.getHeader(headerName);
                    // 将header向下传递
                    requestTemplate.header(headerName, headerValue);

                }
            }
        } else {
            //暂无使用
            Map<String, String> headers = ThreadLocalUtil.get();
            System.out.println("headers:" + headers);
            for (String key : headers.keySet()) {
                requestTemplate.header(key, headers.get(key));
            }
        }
        String xid = RootContext.getXID();
        requestTemplate.header(RootContext.KEY_XID, xid);


    }
}
